package com.zhangyj;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

public class LocalMessage {
	private static final String BASE_NAME = "languageResource";
	private static ThreadLocal<ResourceBundle> localeBundle = new ThreadLocal<ResourceBundle>();

	public static void setLocalBundle(Locale local) {
		localeBundle.set(load(local));
	}

	private static ResourceBundle getBundle() {
		ResourceBundle bundle = localeBundle.get();
		if (bundle == null)
			bundle = load();
		return bundle;
	}

	private static ResourceBundle load(Locale locale) {
		ResourceBundle bundle = null;
		try {
			if (locale == null)
				bundle = PropertyResourceBundle.getBundle(BASE_NAME);
			else
				bundle = PropertyResourceBundle.getBundle(BASE_NAME, locale);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return bundle;
	}

	private static ResourceBundle load() {
		return load(null);
	}

	public static String get(String key) {
		return getBundle().getString(key);
	}

	public static String get(String key, Object[] arguments) {
		return MessageFormat.format(get(key), arguments);
	}

	public static String get(Locale locale, String key) {
		return load(locale).getString(key);
	}

	public static String get(Locale locale, String key, Object[] arguments) {
		return MessageFormat.format(get(locale, key), arguments);
	}
}
